package com.aruba.drawerapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

/**
 * 带有对每个child水平偏移效果的LinearLayout
 */
public class SlideLinearLayout extends LinearLayout {
    //最大偏移量
    private float maxTranslationX;
    private ItemClickListener itemClickListener;

    public SlideLinearLayout(Context context) {
        this(context, null);
    }

    public SlideLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(VERTICAL);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SlideLinearLayout);
        maxTranslationX = typedArray.getDimension(R.styleable.SlideLinearLayout_maxTranslationX, 200);
        typedArray.recycle();
    }

    private View child;
    private int childCenterY;
    private float fraction;

    /**
     * 对每个child有一个不同的水平偏移
     *
     * @param y
     */
    public void layoutChild(float y) {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            child = getChildAt(i);
            //child的y坐标
            childCenterY = (int) (child.getTop() + child.getHeight() / 2f);
            fraction = Math.abs(childCenterY - y) / getHeight() * 3;//放大系数3
            if (fraction < 1) {
                child.setTranslationX(maxTranslationX - fraction * maxTranslationX);
            }
        }
    }

    /**
     * 点击事件
     *
     * @param y
     */
    public boolean onMotionUp(float x, float y) {
        if (itemClickListener == null) {
            return false;
        }

        int position = findChilde(x, y);
        if (position != -1) {
            itemClickListener.onItemClickListener(getChildAt(position), position);
            return true;
        }
        
        return false;
    }

    private int findChilde(float x, float y) {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            Rect r = new Rect();
            child.getGlobalVisibleRect(r);
            if (r.contains((int) x, (int) y)) {
                return i;
            }
        }

        return -1;
    }

    public boolean hasItemClickListener() {
        if (itemClickListener == null)
            return false;

        return true;
    }

    public ItemClickListener getItemClickListener() {
        return itemClickListener;
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public interface ItemClickListener {
        void onItemClickListener(View view, int position);
    }
}
